import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入 store
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout'
  }, {
    path: '/login',
    // 路由的懒加载、当访问这个路由的时候才去加载对应的文件(代码)
    // 提高了首屏加载速度
    component: () => import('@/views/Login')
  }, {
    path: '/layout',
    component: () => import('@/views/Layout'),
    redirect: '/layout/home',
    children: [
      { path: 'home', component: () => import('@/views/Layout/Home') },
      { path: 'mine', component: () => import('@/views/Layout/Mine') }
    ]
  }, {
    path: '/search',
    component: () => import('@/views/Search')
  }, {
    path: '/search/:keyword',
    component: () => import('@/views/SearchResult')
  }, {
    path: '/article',
    component: () => import('@/views/ArticleDetail')
  }, {
    path: '/user/edit',
    component: () => import('@/views/UserEdit')
  }, {
    path: '/robot',
    component: () => import('@/views/Robot')
  }
]

const router = new VueRouter({
  routes
})

// 把不需要登录就可以访问的路由路径写在这个数组中
// 白名单数组
const whiteList = ['/login', '/layout/home', '/search']
// 把需要登录才可访问的路由路径写在这个数组中
// const authList = []
// console.log(whiteList)

// 路由的全局前置守卫
router.beforeEach((to, from, next) => {
  // 获取token
  const { token } = store.state.user
  // 判断有无token
  if (token) { // 登录了
    // 放行
    next()
  } else { // 未登录
    // 如果要去的路由路径在白名单数组中
    if (whiteList.includes(to.path)) {
      // 直接放行
      next()
    } else {
      // 否则，跳转至登录，携带回跳地址
      next(`/login?redirectUrl=${to.path}`)
      // next(): 直接放行
      // next(false): 停留在原地不动
      // next('/path')：跳转至指定路由
    }
  }
})

export default router
